package com.zengyu.toiusuapplication.order;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import com.github.chrisbanes.photoview.PhotoView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.zengyu.toiusuapplication.MainActivity;
import com.zengyu.toiusuapplication.R;
import com.zengyu.toiusuapplication.Utils.SessionManager;
import com.zengyu.toiusuapplication.api.ApiClient;
import com.zengyu.toiusuapplication.api.ApiService;
import com.zengyu.toiusuapplication.model.upLoadComplaintURLModel;
import com.zengyu.toiusuapplication.api.ApiClient;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AllOrderDetailsActivity extends AppCompatActivity {

    private TextView orderIdTextView, addressTextView, latitudeLongitudeTextView,userIdTextView,classificationLabel;
    private TextView network4GLevelTextView, backupTextView, ordercellNameView, createTimeTextView;
    private TextView order_durationLabelTextView, order_userEmotionLabelTextView, order_sceneLabelTextView, order_title_detailsTextView;
    private TextView order_userIssueLabelTextView, order_houseaddressLabelTextView, order_network4GModeLabelTextView;
    private ImageView imageSignal_details, ic_return, imageScene_details, imageSpeed_details, imageCom_details;
    private TextView networkSignalImageLabel,networkSceneImageLabel,networkSpeedImageLabel,networkComImageLabel;
    private Long complaintId;
    private Button deleteOrderButton,modifyOrderButton;
    private AlertDialog progressDialog;
    private LinearLayout buttonContainer;
    private SessionManager sessionManager;
    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        sessionManager = SessionManager.getInstance(this);
        token = sessionManager.getToken();
        setContentView(R.layout.activity_allorder_details);
        ic_return = findViewById(R.id.ic_return);
        orderIdTextView = findViewById(R.id.order_id_details);
        userIdTextView = findViewById(R.id.user_id_details);
        ordercellNameView = findViewById(R.id.order_cellName);
        addressTextView = findViewById(R.id.address_details);
        latitudeLongitudeTextView = findViewById(R.id.latitude_longitude_details);
        network4GLevelTextView = findViewById(R.id.network4g_level_details);
        backupTextView = findViewById(R.id.backup_details);
        createTimeTextView = findViewById(R.id.create_time_details);
        imageSignal_details = findViewById(R.id.imageSignal_details);
        imageScene_details = findViewById(R.id.imageScene_details);
        imageSpeed_details = findViewById(R.id.imageSpeed_details);
        imageCom_details = findViewById(R.id.imageCom_details);
        deleteOrderButton = findViewById(R.id.delete_orderButton);
        modifyOrderButton = findViewById(R.id.modify_orderButton);
        buttonContainer = findViewById(R.id.buttonContainer);
        classificationLabel = findViewById(R.id.classificationLabel);
        order_durationLabelTextView = findViewById(R.id.order_durationLabel);
        order_userEmotionLabelTextView = findViewById(R.id.order_userEmotionLabel);
        order_sceneLabelTextView = findViewById(R.id.order_sceneLabel);
        order_userIssueLabelTextView = findViewById(R.id.order_userIssueLabel);
        order_houseaddressLabelTextView = findViewById(R.id.order_houseaddressLabel);
        order_network4GModeLabelTextView = findViewById(R.id.order_network4GModeLabel);
        order_title_detailsTextView = findViewById(R.id.order_title_details);
        networkSignalImageLabel = findViewById(R.id.networkSignalImageLabel);
        networkSceneImageLabel = findViewById(R.id.networkSceneImageLabel);
        networkSpeedImageLabel = findViewById(R.id.networkSpeedImageLabel);
        networkComImageLabel = findViewById(R.id.networkComImageLabel);

        Intent intent = getIntent();
        complaintId = intent.getLongExtra("OrderDetailsComplaintId", -1);

        if (complaintId != -1) {
            fetchComplaintById(complaintId);
        } else {
            Toast.makeText(this, "数据加载失败", Toast.LENGTH_SHORT).show();
            finish();
        }

        ic_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                finish();
            }
        });
    }

    private void fetchComplaintById(Long complaintId) {
        SessionManager sessionManager = new SessionManager(this);
        String token = sessionManager.getToken();
        ApiService apiService = ApiClient.getApiService();
        Call<ResponseBody> call = apiService.getComplaintbyId(complaintId);

        progressDialog = createProgressDialog();
        progressDialog.show();
        if (sessionManager.isTokenValid() && !token.isEmpty()) {
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        try {
                            String jsonString = response.body().string();
                            Gson gson = new Gson();
                            upLoadComplaintURLModel complaint = gson.fromJson(jsonString, upLoadComplaintURLModel.class);
                            // 展示详情内容
                            displayComplaintDetails(complaint);
                            // 加载图片
                            loadImages(complaint);
                            // 判断是否显示修改/删除按钮
                            setupButtons(complaint);

                        } catch (IOException | JsonSyntaxException e) {
                            Toast.makeText(AllOrderDetailsActivity.this, "解析失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(AllOrderDetailsActivity.this, "数据加载失败", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                    progressDialog.dismiss();
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    progressDialog.dismiss();
                    Toast.makeText(AllOrderDetailsActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_LONG).show();
                    finish();
                }
            });
        }
    }

    private void loadImages(upLoadComplaintURLModel complaint) {
        loadImage(imageSignal_details, complaint.getImageSignalURL());
        loadImage(imageScene_details, complaint.getImageSceneURL());
        loadImage(imageSpeed_details, complaint.getImageSpeedURL());
        loadImage(imageCom_details, complaint.getImageCommunicationURL());
    }

    private void loadImage(ImageView imageView, String imageUrl) {
        if (imageUrl == null || imageUrl.isEmpty()) {
            imageView.setImageResource(R.drawable.image1);
            imageView.setOnClickListener(null);
            return;
        }

        String fullUrl = ApiClient.base_ImageUrl + imageUrl;

        // 使用 Glide 加载缩略图
        Glide.with(this)
                .load(fullUrl)
                .placeholder(R.drawable.image1)
                .error(R.drawable.error_image)
                .into(imageView);

        // 设置点击事件打开预览
        imageView.setOnClickListener(v -> showImagePreview(fullUrl));
    }


    private void setupButtons(upLoadComplaintURLModel complaint) {
        if (MainActivity.UserId.equals(complaint.getUserId())) {
            buttonContainer.setVisibility(View.VISIBLE);
            modifyOrderButton.setOnClickListener(v -> modifyOrder(complaint.getId()));
            deleteOrderButton.setOnClickListener(v -> deleteOrder(complaint.getId()));
        } else {
            buttonContainer.setVisibility(View.GONE);
        }
    }

    private void displayComplaintDetails(upLoadComplaintURLModel complaint) {
        orderIdTextView.setText("订单ID: " + complaint.getId());
        userIdTextView.setText("提交人ID: " + complaint.getUserId());
        classificationLabel.setText("分类: " + complaint.getClassificationLabel());
        order_title_detailsTextView.setText("标题: " + complaint.getTitle());
        addressTextView.setText("投诉地址: " + complaint.getAddress());
        latitudeLongitudeTextView.setText("经纬度: " + complaint.getLatitudeLongitude());
        network4GLevelTextView.setText("电平: " + complaint.getNetwork4GLevel());
        ordercellNameView.setText("小区名: " + complaint.getCellName());
        createTimeTextView.setText("创建时间: " + formatCreateTime(complaint.getCreatedTime()));
        order_durationLabelTextView.setText("持续时间: " + complaint.getDuration());
        order_userEmotionLabelTextView.setText("客户情绪: "+ complaint.getUserEmotion());
        order_sceneLabelTextView.setText("投诉场景: " + complaint.getScene());
        order_userIssueLabelTextView.setText("客户问题现象: " + complaint.getUserIssue());
        order_houseaddressLabelTextView.setText("投诉单点建筑描述: " + complaint.getHouseaddress());
        order_network4GModeLabelTextView.setText("手机上网模式+语音方案: " + complaint.getNetworkMode());
        networkSignalImageLabel.setText("信号测试图: " + complaint.getImageSignalURL());
        networkSceneImageLabel.setText("现场照片: " + complaint.getImageSceneURL());
        networkSpeedImageLabel.setText("速率测试图: " + complaint.getImageSpeedURL());
        networkComImageLabel.setText("客户沟通图: " + complaint.getImageCommunicationURL());

        if (!complaint.getBackup().isEmpty()) {
            backupTextView.setText("备注: " + complaint.getBackup());
        } else {
            backupTextView.setText("备注: ");
        }
    }

    private String formatCreateTime(String createTime) {
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date date = inputFormat.parse(createTime);
            return outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return createTime; // Return the original string if parsing fails
        }
    }

    private void showImagePreview(String imageUri) {
        Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
        dialog.setContentView(R.layout.dialog_image_preview);
        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        // 设置点击背景关闭 Dialog
        View backgroundView = dialog.findViewById(R.id.background_view);
        backgroundView.setOnClickListener(v -> dialog.dismiss());
        // 加载图片到 PhotoView
        PhotoView photoView = dialog.findViewById(R.id.photoView);
        Glide.with(this).load(imageUri).into(photoView);
        // 点击图片也关闭 Dialog
        photoView.setOnClickListener(v -> dialog.dismiss());

        dialog.show();
    }

    private AlertDialog createProgressDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_progress, null);
        builder.setView(view);

        TextView titleTextView = view.findViewById(R.id.progress_title);
        titleTextView.setText("正在加载...");

        // 设置关闭按钮为 ImageView
        ImageView closeButton = view.findViewById(R.id.close_button);
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressDialog.dismiss();
            }
        });

        final AlertDialog dialog = builder.create();
        dialog.show();
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }

    private void modifyOrder(Long orderId){
        Intent intent = new Intent(AllOrderDetailsActivity.this, ModifyDetailsActivity.class);
        intent.putExtra("modifyId",orderId);
        startActivity(intent);
    }

    private void deleteOrder(Long orderId) {
        // 显示确认对话框
        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定要删除此订单及所有关联图片吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 执行删除操作
                        ApiService apiService = ApiClient.getApiService();
                        Call<Void> call = apiService.deleteComplaint(orderId);
                        call.enqueue(new Callback<Void>() {
                            @Override
                            public void onResponse(Call<Void> call, Response<Void> response) {
                                if (response.isSuccessful()) {
                                    // 跳转到首页
                                    Intent intent = new Intent(AllOrderDetailsActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish(); // 关闭当前活动
                                    Toast.makeText(AllOrderDetailsActivity.this, "订单已删除", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(AllOrderDetailsActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onFailure(Call<Void> call, Throwable t) {
                                Toast.makeText(AllOrderDetailsActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        progressDialog.dismiss();
                    }
                })
                .show();
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}

